import sqlite3
import os

def clear_messages():
    # 连接到数据库
    db_path = 'aichat.db'
    if not os.path.exists(db_path):
        print(f"数据库文件 {db_path} 不存在")
        return False
    
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    try:
        # 检查messages表是否存在
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='messages'")
        if not cursor.fetchone():
            print("messages表不存在")
            return False
        
        # 获取messages表的记录数
        cursor.execute("SELECT COUNT(*) FROM messages")
        count = cursor.fetchone()[0]
        print(f"messages表中有 {count} 条记录")
        
        if count == 0:
            print("messages表已经是空的")
            return True
        
        # 删除所有记录
        cursor.execute("DELETE FROM messages")
        conn.commit()
        
        # 验证删除结果
        cursor.execute("SELECT COUNT(*) FROM messages")
        remaining = cursor.fetchone()[0]
        
        print(f"成功删除 {count - remaining} 条记录，剩余 {remaining} 条记录")
        return True
        
    except Exception as e:
        print(f"删除messages表记录时出错: {str(e)}")
        conn.rollback()
        return False
    finally:
        conn.close()

if __name__ == "__main__":
    print("开始清理messages表...")
    success = clear_messages()
    if success:
        print("messages表清理完成")
    else:
        print("messages表清理失败")